<!--
 * @Descripttion: 编辑轮播图
 * @Author: xiao li
 * @Date: 2020-09-30 10:32:19
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-19 17:13:46
-->
<template>
  <div class="lb-ordering-editPrint">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <div style="height: 40px"></div>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="subForm"
        label-width="120px"
        class="basic-form"
      >
        <el-form-item label="封面图" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 400</lb-tool-tips>
        </el-form-item>
        <el-form-item label="是否添加跳转" prop="jump_status">
          <el-radio-group v-model="subForm.jump_status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form
          @submit.native.prevent
          :model="subForm"
          :rules="jumpFormRules"
          ref="jumpForm"
          label-width="120px"
          class="basic-form"
          v-if="subForm.jump_status === 1"
        >
          <el-form-item label="跳转类型" prop="jump_type">
            <el-radio-group @change="radioChange" v-model="subForm.jump_type">
              <el-radio :label="1">拨打电话</el-radio>
              <el-radio :label="2">其他小程序</el-radio>
              <el-radio :label="3">网页链接</el-radio>
              <el-radio :label="4">小程序内部链接</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="link_url">
            <el-tag
              v-if="subForm.jump_type === 4"
              :closable="cur_info.title ? true : false"
              @close="delCurInfo"
              @click="open"
              >{{ cur_info.title || '选择链接' }}</el-tag
            >
            <el-input
              v-model="subForm.link_url"
              :placeholder="jumpType[subForm.jump_type]"
              v-else
            ></el-input>
            <lb-tool-tips
              >小程序跳转链接填写格式如下:
              <div class="mt-md">
                1、跳转到小程序首页
                <div class="mt-md c-link">
                  所需参数如下：
                  <div class="mt-sm">[1] appId</div>
                </div>
                <div class="mt-md">例如：wx581f0c1732ae745f</div>
              </div>
              <div class="mt-lg">
                2、跳转到小程序指定页面
                <div class="mt-md c-link">
                  所需参数如下：
                  <div class="mt-sm">[1] appId</div>
                  <div class="mt-sm">[2] ; (英文状态下的分号)</div>
                  <div class="mt-sm">[3] 页面路径及参数</div>
                </div>
                <div class="mt-md">
                  例如：wx581f0c1732ae745f;pages/user/home?key=1&staff_id=1
                </div>
              </div>
            </lb-tool-tips>
          </el-form-item>
        </el-form>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitFormInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 选择可用链接 -->

    <el-dialog
      title="选择链接"
      :visible.sync="visible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
    >
      <div v-loading="loading">
        <div class="dialog-module-list">
          <div
            class="dialog-module-item"
            :class="{ 'dialog-module-item--select': index == activeIndex }"
            v-for="(item, index) in moduleList"
            :key="index"
            @click="moduleClick(index)"
          >
            {{ item.title }}
          </div>
        </div>
        <div style="display: flex" v-if="moduleList.length > 0">
          <div class="dialog-left">
            <div class="dialog-left_title">
              {{ moduleList[activeIndex].title }}链接
            </div>
            <div
              class="dialog-left_item"
              :class="{ 'dialog-left_item--select': aindex == cactiveIndex }"
              v-for="(aitem, aindex) in moduleList[activeIndex].data"
              :key="aindex"
              @click="moduleChildClick(aindex)"
            >
              {{ aitem.title }}
            </div>
          </div>
          <div
            style="flex: 1"
            v-if="moduleList[activeIndex].data[cactiveIndex].api_path"
          >
            <div
              class="text-right mb-lg"
              v-if="
                moduleList[activeIndex].data[cactiveIndex].page !==
                'common_page'
              "
            >
              <el-input
                v-model="searchForm.keyword"
                placeholder="请输入名称搜索"
                size="small"
              ></el-input>
              <el-button
                type="primary"
                @click="search"
                size="small"
                style="margin-left: 10px"
                >搜索</el-button
              >
            </div>

            <el-table
              ref="singleTable"
              :data="tableData"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
              @current-change="handleCurrentChange"
              v-loading="tableLoading"
              :highlight-current-row="true"
            >
              <el-table-column
                prop="id"
                label="ID"
                width="150"
                v-if="
                  moduleList[activeIndex].data[cactiveIndex].page !==
                  'common_page'
                "
              ></el-table-column>
              <el-table-column prop="title" label="名称"></el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer-diy">
        <div class="dialog-footer_op">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </div>
        <el-pagination
          v-if="
            moduleList.length > 0 &&
            moduleList[activeIndex].data[cactiveIndex].api_path &&
            moduleList[activeIndex].data[cactiveIndex].page !== 'common_page'
          "
          @size-change="handleSizeChange"
          @current-change="handlePageCurrentChange"
          :total="total"
          :current-page="searchForm.page"
          :page-size="searchForm.page_count"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { get } from '../../../api/index'
export default {
  data () {
    let validateJump = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.jumpType[this.subForm.jump_type]))
      } else {
        callback()
      }
    }
    return {
      navTitle: '',
      cur_info: { title: '', url: '' },
      jumpType: {
        1: '请输入电话号码', 2: '请输入小程序appid', 3: '请输入网页链接', 4: '请选择系统内部链接'
      },
      subForm: {
        id: 0,
        cover: '',
        jump_status: 1,
        jump_type: 1,
        link_url: '',
        link_title: '',
        top: 0,
        status: 1
      },
      subFormRules: {
        cover: {
          required: true,
          type: 'array',
          message: '请上传图片',
          trigger: 'change'
        },
        jump_status: { required: true },
        top: {
          required: true,
          type: 'number',
          message: '请输入排序值',
          trigger: 'blur'
        }
      },
      jumpFormRules: {
        jump_type: { required: true },
        link_url: {
          required: true,
          validator: validateJump,
          trigger: 'blur'
        }
      },
      visible: false,
      moduleList: [],
      activeIndex: 0,
      cactiveIndex: 0,
      searchForm: {
        page: 1,
        limit: 10,
        page_count: 10,
        keyword: '',
        status: 1,
        diy_id: 0,
        key: 2
      },
      total: 0,
      loading: false,
      tableLoading: false
    }
  },
  async created () {
    let { id } = this.$route.query
    this.navTitle = this.$t(id ? 'menu.PayclassBannerEdit' : 'menu.PayclassBannerAdd')
    await this.getDiyIng()
    if (id) {
      this.subForm.id = id
      await this.getDetail(id)
    }
  },
  methods: {
    radioChange (e) {
      // alert(e)
      let { title = '', url = '' } = this.cur_info
      this.subForm.link_url = e === 4 ? url : ''
      this.subForm.link_title = e === 4 ? title : ''
    },
    /**
     * @method: 获取当前DIY的id
     */
    async getDiyIng () {
      let { code, data } = await this.$api.diyIng()
      if (code !== 200) return
      this.searchForm.diy_id = data
    },
    /**
     * @method 获取封面图
     */
    getCover (img) {
      this.subForm.cover = img
    },
    /**
     * @method: 获取轮播图详情
     */
    async getDetail (id) {
      let { code, data } = await this.$api.payclassBannerInfo({ id })
      if (code !== 200) return
      for (let key in this.subForm) {
        if (key === 'cover') {
          data[key] = [{ url: data[key] }]
        }
        this.subForm[key] = data[key]
      }
      if (data.jump_type !== 4) return
      this.cur_info = {
        title: data.link_title,
        url: data.link_url
      }
    },
    handleCurrentChange (val) {
      this.currentRow = val
    },
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.searchForm.page_count = val
      this.handlePageCurrentChange(1)
    },
    handlePageCurrentChange (val) {
      this.searchForm.page = val
      this.getList()
    },
    submit () {
      let moduleItem = this.moduleList[this.activeIndex]
      if (!moduleItem) {
        this.$message.error('请选择')
        return
      }
      let item = moduleItem.data[this.cactiveIndex]
      if (!item) {
        this.$message.error('请选择')
        return
      }
      let obj = {
        title: item.title,
        url: item.page
      }
      if (item.api_path) {
        if (!this.currentRow) {
          this.$message.error('请点击列表选择一项')
          return
        } else {
          let { id = 0, title = '' } = this.currentRow
          obj.title = title || '无标题'
          let arr = ['common_page']
          let arr2 = ['/pages/shop/detail']
          let curURL = obj.url
          obj.url = `${curURL}?id=${id}&title=${title}`
          if (arr.includes(curURL)) {
            obj.url = `${this.currentRow.path}`
          }
          if (arr2.includes(curURL)) {
            obj.url = `${curURL}?id=${id}&staff_id=`
          }
        }
      }
      this.cur_info = obj
      this.subForm.link_url = obj.url
      this.subForm.link_title = obj.title
      this.visible = false
    },
    moduleClick (index) {
      this.activeIndex = index
      this.cactiveIndex = 0
      this.searchForm.page = 1
      this.searchForm.limit = 10
      this.searchForm.page_count = 10
      this.searchForm.keyword = ''
      this.getList()
    },
    moduleChildClick (index) {
      this.cactiveIndex = index
      this.searchForm.page = 1
      this.searchForm.limit = 10
      this.searchForm.page_count = 10
      this.searchForm.keyword = ''
      this.getList()
    },
    search () {
      this.searchForm.page = 1
      this.getList()
    },
    async open () {
      this.visible = true
      this.loading = true
      let res = await this.$api.getMoudelByKey({ key: 2 })
      this.loading = false
      if (res.code === 200) {
        this.moduleList = res.data
        this.getList()
      }
    },
    async getList () {
      let item = this.moduleList[this.activeIndex].data[this.cactiveIndex]
      if (!item.api_path) {
        this.tableData = []
        this.total = 0
        return
      }
      let searchForm = JSON.parse(JSON.stringify(this.searchForm))
      this.tableLoading = true
      let res = await get(item.api_path, searchForm)
      this.tableLoading = false
      if (res.code === 200) {
        this.tableData = res.data.data
        this.total = res.data.total
      }
    },
    delCurInfo () {
      this.cur_info = { title: '', url: '' }
    },
    async submitFormInfo () {
      let title = JSON.parse(JSON.stringify(this.subForm.link_url)).replace(/^\s+|\s+$/g, '')
      this.subForm.link_url = title
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      let formArr = ['subForm']
      if (subForm.jump_status === 1) {
        formArr.push('jumpForm')
      }
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        subForm.cover = subForm.cover[0].url
        let methodModel = subForm.id ? 'payclassBannerUpdate' : 'payclassBannerAdd'
        let { code } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.$message.success(this.$t('tips.successSub'))
        this.$router.back(-1)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-ordering-editPrint {
  width: 100%;
  .el-input,
  .el-select,
  .lb-input-number,
  .el-cascader {
    width: 300px;
  }
  .flex-warp {
    .el-select {
      width: 230px;
    }
  }
}
.form-label {
  width: 90px;
  margin-left: 10px;
}

.el-input,
.el-select,
.el-cascader {
  width: 208px;
}
</style>
